import { Button, Radio, RadioChangeEvent } from "antd";
import PropTypes from "prop-types";
import React, { FC, memo, ReactNode, SetStateAction, useState } from "react";
import { useDispatch } from "react-redux";
import { BaseSelectionWrapper } from "./style";

import coffeeSelection, {
  changeSizeSelection,
  changeIceSelection,
  changeSugerSelection,
} from "@/store/modules/coffeeSelection";
import { useEffect } from "react";
import { useAppSelector } from "@/store";

interface Iprops {
  children?: ReactNode;
  title: string;
  content: SetStateAction<{}>;
}

const BaseSelectionBox: FC<Iprops> = memo((props) => {
  const { title, content } = props;

  const { coffeeSelection } = useAppSelector((state) => ({
    coffeeSelection: state.coffeeSelection,
  }));

  const dispatch = useDispatch();

  const [value, setValue] = useState(Object.keys(content)[0]);
  useEffect(() => {
    switch (title) {
      case "尺寸":
        setValue(coffeeSelection.size);
        break;
      case "温度":
        setValue(coffeeSelection.iceLevel);
        break;
      case "糖度":
        setValue(coffeeSelection.sugerLevel);
        break;
    }
  }, [
    coffeeSelection.iceLevel,
    coffeeSelection.size,
    coffeeSelection.sugerLevel,
    title,
  ]);

  const btnClick = (e: RadioChangeEvent) => {
    setValue(e.target.value);
    switch (title) {
      case "尺寸":
        dispatch(changeSizeSelection(e.target.value));
        break;
      case "温度":
        dispatch(changeIceSelection(e.target.value));
        break;
      case "糖度":
        dispatch(changeSugerSelection(e.target.value));
        break;
    }
  };

  return (
    <BaseSelectionWrapper>
      <div className="title">{title}</div>
      <div>
        {Object.keys(content)[0] && (
          <Radio.Group
            //默认为第一个
            defaultValue={Object.keys(content)[0]}
            value={value}
            size="large"
            buttonStyle="solid"
            onChange={(e) => btnClick(e)}
            className="btnGroup"
          >
            {Object.keys(content).map((key) => {
              return (
                <Radio.Button className="btn" value={key} key={key}>
                  {content[key as keyof SetStateAction<{}>]}
                </Radio.Button>
              );
            })}
          </Radio.Group>
        )}
      </div>
    </BaseSelectionWrapper>
  );
});

export default BaseSelectionBox;
